Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

530
Vistas
Mongo $push operator do not accept object according to typescript: "No overload matches this call"

I want to push a message in an array with Mongoose/Mongo. Typescript claims that:

No overload matches this call. Overload 1 of 3, '(id: any, update: UpdateQuery, options: QueryOptions & { rawResult: true; }, callback?: ((err: any, doc: FindAndModifyWriteOpResultObject, res: any) => void) | undefined): any', gave the following error. Type '{ messages: { message: string; authorId: string; }; }' is not assignable to type 'PushOperator<_AllowStringsForIds<Pick<Pick<_LeanDocument, string | number | symbol>, string | number | symbol>>>'. Type '{ messages: { message: string; authorId: string; }; }' is not assignable to type 'NotAcceptedFields<_AllowStringsForIds<Pick<Pick<_LeanDocument, string | number | symbol>, string | number | symbol>>, readonly any[]>'. Property 'messages' is incompatible with index signature.

Here is the code snippet:

    const conversation = await Conversation.findByIdAndUpdate(
      conversationId,
      {
        $push: { messages: { message, authorId } },
        lastMessage: {
          authorId,
          snippet: `${message.substring(0, 47)}...`,
          read: false,
        },
      },
      { new: true }
    );

The build crash because of this. How to fix it?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

This is an issue with types not lining up.

My understanding is the push operation can only be done on a field that is explicitly defined as an array at some point in your code previously.

A potential solution is to explicitly set the type of your collection to contain the fields you want (which is good practice anyway).

So rather than something along the lines of

const Conversations = database.collection('conversations');

You would explicitly define the schema for the 'conversation' documents, and then type the collection:

import { Collection } from 'mongodb';
//...
type Conversation = {
  messages: { message: String, authorId: Number }[],
//...
}

const Conversations: Collection<Conversation> = database.collection('conversations');
over 4 years ago · Santiago Trujillo Denunciar

0

If you know you're doing the right thing, then you can bypass this with as.

The following example illustrates this.

await driver.collection('myCollection').findOneAndUpdate(
    {
        _id: "<some _id that I have>",
    },
    {
        '$push': {
            'myArrayField': {
                '$position': 0,
                '$each': [ myItemToPush ],
             }
         } as unknown as PushOperator<Document>,
     },
     {
         returnDocument: 'after',
         upsert: false,
     },
 );

Note the as unknown as PushOperator<Document> - this is what's going to get you out of this problem. Use it properly as Tyscript will allow you to use as anywhree and used unabated, this can defeat the purpose of using a type system.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda